// FILEPATH: d:/code/money/match-management/src/modules/role/role.service.ts

import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from './entities/role.entity';
import { PermissionService } from '../permission/permission.service';
import { RoleEnum } from 'src/common/constant/enums';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private readonly repository: Repository<Role>,
    private readonly permissionService: PermissionService,
  ) {}

  async create(createRoleDto: CreateRoleDto) {
    const role = this.repository.create(createRoleDto);
    return this.repository.save(role);
  }

  async findAll() {
    return this.repository.find();
  }

  findOne(id: number) {
    // return this.repository.findOne({
    //   where: { id },
    //   relations: ['permissions'],
    // });
    return this.repository
      .createQueryBuilder('role')
      .leftJoinAndSelect('role.permissions', 'permission')
      .where('role.id = :id', { id })
      .getOne();
  }

  update(id: number, updateRoleDto: UpdateRoleDto) {
    return this.repository.update(id, updateRoleDto);
  }

  remove(id: number) {
    return this.repository.delete(id);
  }

  async addPermission(roleId: number, permissionIds: number[]) {
    const role = await this.findOne(roleId);
    const permissions = await this.permissionService.listByIds(permissionIds);
    role.permissions = [...role.permissions, ...permissions];

    return this.create(role);
  }
  async findByName(name: RoleEnum) {
    // return await this.repository.findOne({ where: { name } });
    return this.repository
      .createQueryBuilder('role')
      .leftJoinAndSelect('role.permissions', 'permission')
      .where('role.name = :name', { name })
      .getOne();
  }
}
